<template>
  <div class="record-container">
    <el-button
      type="primary"
      :icon="ArrowLeft"
      plain
      @click="$router.go(-1)"
      style="margin-bottom: 20px"
    >
      返回主菜单
    </el-button>
    <div class="company-step-container">
      <div class="company-main-row">
        <div class="company-step-side">
          <el-steps
            :active="activeStep"
            class="mb-4"
            :space="200"
            simple
            @change="handleStepChange"
          >
            <el-step
              v-for="(item, idx) in steps"
              :key="item.value"
              :title="item.label"
              :icon="item.icon"
              simple
              @click.native="goStep(idx)"
            />
          </el-steps>
        </div>
        <div class="company-main-content">
          <div v-show="activeStep === 0" class="record-content">
            <div class="material-upload-row stacked">
              <!-- 左侧备案材料 -->
              <el-card class="material-block" shadow="never">
                <div class="block-title">
                  备案材料
                  <el-icon
                    class="tip-icon"
                    @click="handleFilePreview(id_example_test, '示例图')"
                  >
                    <QuestionFilled />
                  </el-icon>
                  <span
                    class="tip-text"
                    @click="handleFilePreview(id_example_test, '示例图')"
                    >备案流程说明</span
                  >
                </div>
                <div class="material-inner-row">
                  <div class="upload-vertical">
                    <div class="upload-section">
                      <div class="upload-label">
                        <span style="color: red; margin-right: 5px">*</span
                        >备案表<el-button
                          type="primary"
                          link
                          size="small"
                          style="margin-left: 8px"
                          @click="downloadTemplate"
                          >下载模板</el-button
                        >
                      </div>
                      <el-upload
                        class="upload-demo"
                        :show-file-list="true"
                        :auto-upload="true"
                        :file-list="fileListRecord"
                        :before-upload="(file) => beforeUpload(file, 0)"
                        :on-change="(f, fl) => handleFileChange('record', f, fl)"
                        :on-preview="(file) => handleFilePreview(file, 'record')"
                        :on-remove="(file) => handleFileRemove('record', file)"
                        accept="*"
                        list-type="text"
                      >
                        <el-button type="primary">上传备案表</el-button>
                      </el-upload>
                      <div class="upload-label">
                        <span style="color: red; margin-right: 5px">*</span>备案情况说明
                      </div>
                      <el-upload
                        class="upload-demo"
                        :show-file-list="true"
                        :auto-upload="true"
                        :file-list="fileListRecordOk"
                        :before-upload="(file) => beforeUpload(file, 13)"
                        :on-change="(f, fl) => handleFileChange('record_ok', f, fl)"
                        :on-preview="(file) => handleFilePreview(file, 'record_ok')"
                        :on-remove="(file) => handleFileRemove('record_ok', file)"
                        accept="*"
                        list-type="text"
                      >
                        <el-button type="primary">上传备案情况说明</el-button>
                      </el-upload>
                    </div>
                    <!-- 新注册才显示信息注册表 -->
                    <div class="upload-section" v-if="companyClass !== '迁址'">
                      <div class="upload-label">
                        <span style="color: red; margin-right: 5px">*</span>信息注册表
                        <el-button
                          type="primary"
                          link
                          size="small"
                          style="margin-left: 8px"
                          @click="downloadDesc"
                          >下载模板</el-button
                        >
                      </div>
                      <el-upload
                        class="upload-demo"
                        :show-file-list="true"
                        :auto-upload="true"
                        :file-list="fileListInfo"
                        :before-upload="(file) => beforeUpload(file, 1)"
                        :on-change="(f, fl) => handleFileChange('info', f, fl)"
                        :on-preview="(file) => handleFilePreview(file, 'info')"
                        :on-remove="(file) => handleFileRemove('info', file)"
                        accept="*"
                        list-type="text"
                      >
                        <el-button type="primary">上传信息注册表</el-button>
                      </el-upload>
                    </div>
                  </div>
                  <div class="block-img"></div>
                </div>
              </el-card>
              <!-- 右侧办证材料 -->
              <el-card class="material-block" shadow="never">
                <div class="block-title">
                  办证材料
                  <el-icon
                    class="tip-icon"
                    @click="handleFilePreview(licenseExample, '示例图')"
                  >
                    <QuestionFilled />
                  </el-icon>
                  <span
                    class="tip-text"
                    @click="handleFilePreview(licenseExample, '示例图')"
                    >办证流程说明</span
                  >
                </div>
                <div class="material-inner-row">
                  <div class="upload-vertical">
                    <div class="upload-section">
                      <div class="upload-label">法人签字笔迹</div>
                      <el-upload
                        class="upload-demo"
                        :show-file-list="true"
                        :auto-upload="true"
                        :file-list="fileListSign"
                        :before-upload="(file) => beforeUpload(file, 2)"
                        :on-change="(f, fl) => handleFileChange('sign', f, fl)"
                        :on-preview="(file) => handleFilePreview(file, 'sign')"
                        :on-remove="(file) => handleFileRemove('sign', file)"
                        :multiple="true"
                        accept="image/*"
                      >
                        <el-button type="primary">上传法人签字笔迹</el-button>
                      </el-upload>
                    </div>
                    <div class="upload-section">
                      <div class="upload-label">自然人身份证</div>
                      <el-upload
                        class="upload-demo"
                        :show-file-list="true"
                        :auto-upload="true"
                        :file-list="fileListId"
                        :before-upload="(file) => beforeUpload(file, 3)"
                        :on-change="(f, fl) => handleFileChange('id', f, fl)"
                        :on-preview="(file) => handleFilePreview(file, 'id')"
                        :on-remove="(file) => handleFileRemove('id', file)"
                        :multiple="true"
                        accept="image/*"
                      >
                        <el-button type="primary">上传自然人身份证</el-button>
                      </el-upload>
                    </div>
                    <div class="upload-section">
                      <div class="upload-label">非自然人营业执照</div>
                      <el-upload
                        class="upload-demo"
                        :show-file-list="true"
                        :auto-upload="true"
                        :file-list="fileListLicense"
                        :before-upload="(file) => beforeUpload(file, 4)"
                        :on-change="(f, fl) => handleFileChange('license', f, fl)"
                        :on-preview="(file) => handleFilePreview(file, 'license')"
                        :on-remove="(file) => handleFileRemove('license', file)"
                        :multiple="true"
                        accept="image/*"
                      >
                        <el-button type="primary">上传非自然人营业执照</el-button>
                      </el-upload>
                    </div>
                  </div>
                  <div class="block-img"></div>
                </div>
              </el-card>
            </div>

            <!-- 步骤操作按钮 -->
            <div style="margin-top: 32px; display: flex; gap: 16px">
              <el-button @click="handlePrevStep" :disabled="activeStep === 0"
                >上一步</el-button
              >
              <el-button
                @click="handleNextStep"
                v-if="!shouldShowCompleteButton"
                :disabled="activeStep === steps.length - 1"
                >下一步</el-button
              >
              <el-button
                :disabled="!shouldShowCompleteButton"
                v-if="shouldShowCompleteButton"
                type="success"
                @click="handleCompleteRecordStep('备案')"
              >
                完成备案
              </el-button>
            </div>
          </div>
          <div v-show="activeStep === 1" class="contract-content">
            <!-- 合同类型Tab（只保留虚拟） -->
            <el-tabs v-model="contractType" @tab-click="handleTabChange">
              <el-tab-pane label="虚拟" name="虚拟"></el-tab-pane>
            </el-tabs>
            <div class="material-upload-row" style="display: block">
              <!-- 虚拟表单 -->
              <el-card
                v-if="contractType === '虚拟'"
                class="material-block"
                shadow="never"
                body-style="width: 100%; "
                style="max-width: 100%; min-width: 400px"
              >
                <div class="block-title">合同拟定（虚拟）</div>
                <el-form
                  :model="contractForm"
                  ref="contractFormRef"
                  label-width="110px"
                  label-position="left"
                  :disabled="contractForm.approvalNo"
                >
                  <el-row :gutter="16">
                    <el-col :span="12">
                      <el-form-item label="合同编号" prop="contractNumber">
                        <el-input
                          v-model="contractForm.contractNumber"
                          placeholder="合同编号（自动生成）"
                          disabled
                          style="width: calc(100% - 120px); display: inline-block"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item>
                        <span
                          v-if="!contractForm.contractNumber"
                          style="color: red; margin-right: 5px"
                          >*</span
                        ><el-button
                          v-if="!contractForm.contractNumber"
                          type="primary"
                          style="margin-left: 8px; vertical-align: top"
                          @click="handleGenerateContractNumber"
                          >生成合同编号</el-button
                        >
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-divider>出租方信息</el-divider>
                  <el-row :gutter="16">
                    <el-col :span="24">
                      <el-form-item label="名称" prop="lessorName">
                        <el-input
                          v-model="contractForm.carrierInfo.lessorName"
                          placeholder="请输入出租方名称"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-divider>承租方信息</el-divider>
                  <el-row :gutter="16">
                    <el-col :span="24">
                      <el-form-item label="名称" prop="lesseeName">
                        <el-input
                          v-model="contractForm.lesseeName"
                          placeholder="请输入承租方名称"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-divider>租赁物信息</el-divider>
                  <el-row :gutter="16">
                    <el-col :span="12">
                      <el-form-item label="项目地址" prop="address">
                        <el-input
                          v-model="contractForm.address"
                          placeholder="请输入项目地址"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="房号" prop="roomNumber">
                        <el-select
                          v-model="contractForm.roomNumber"
                          placeholder="请选择房号"
                          filterable
                          multiple
                          style="width: 100%"
                          @change="handleRoomChange"
                        >
                          <el-option
                            v-for="item in freeRooms"
                            :key="item.id"
                            :label="`${item.zt} - ${
                              item.assetType === 0 ? '房间' : '工位'
                            }：${item.roomNumber}（${getRoomStatusText(item.status)}）`"
                            :value="item.roomNumber"
                          >
                            <span>
                              {{ item.zt }} -
                              {{ item.assetType === 0 ? "房间" : "工位" }}：{{
                                item.roomNumber
                              }}（{{ getRoomStatusText(item.status) }}）
                            </span>
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="16">
                    <el-col :span="8">
                      <el-form-item label="面积" prop="area">
                        <el-input
                          v-model="contractForm.area"
                          type="number"
                          min="0"
                          placeholder="请输入面积"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="租赁年限" prop="year">
                        <el-input
                          v-model="contractForm.year"
                          type="number"
                          min="1"
                          placeholder="请输入租赁年限（年）"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="16">
                    <el-col :span="12">
                      <el-form-item label="租赁期限" prop="leaseTerm">
                        <el-date-picker
                          v-model="leaseDateRange_start"
                          type="date"
                          placeholder="请选择租赁开始日期"
                          format="YYYY年MM月DD日"
                          value-format="YYYY-MM-DD"
                          style="width: 100%"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="金额" prop="amount">
                        <el-input
                          v-model="contractForm.amount"
                          type="number"
                          min="0"
                          placeholder="请输入金额"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="16">
                    <el-col :span="24">
                      <el-form-item label="其他约定事项" prop="message">
                        <el-input
                          v-model="contractForm.message"
                          type="textarea"
                          placeholder="请输入其他约定事项"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="16">
                    <el-col :span="4">
                      <el-form-item>
                        <span style="color: red; margin-right: 5px">*</span>
                        <el-button type="primary" @click="handleDraftContract"
                          >信息保存</el-button
                        >
                      </el-form-item>
                    </el-col>
                    <el-col :span="4">
                      <el-form-item>
                        <span style="color: red; margin-right: 5px" v-if="contractForm.id"
                          >*</span
                        >
                        <el-button
                          type="primary"
                          @click="handleCreatedDraftContract"
                          v-if="contractForm.id"
                          >生成合同</el-button
                        >
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>
              </el-card>

              <div class="material-upload-row" v-if="contractForm.id">
                <!-- 虚拟合同盖章归档 -->
                <el-card
                  v-if="contractType === '虚拟'"
                  class="material-block"
                  shadow="never"
                  style="width: 100%; min-width: 320px; margin-top: 30px"
                >
                  <div class="block-title">合同盖章归档</div>
                  <el-form label-width="110px" label-position="top" :inline="true">
                    <!-- <el-form-item label="用印类型">
                      <el-radio-group v-model="sealVirtualType">
                        <el-radio label="实体章">实体章</el-radio>
                        <el-radio label="电子章">电子章</el-radio>
                      </el-radio-group>
                    </el-form-item>
                    <el-form-item label="创建日期">
                      <el-date-picker
                        v-model="createTimeVirtual"
                        type="date"
                        placeholder="请选择创建日期"
                        format="YYYY年MM月DD日"
                        value-format="YYYY-MM-DD"
                        style="width: 100%"
                      /> -->
                    <!-- </el-form-item> -->
                    <!-- <el-form-item label="审批单号">
                      <el-input
                        v-model="approvalVirtualNumber"
                        disabled
                        placeholder="请输入用印审批单号"
                      />
                    </el-form-item> -->
                    <el-form-item>
                      <span style="text-align: center; margin-top: 5px">会签人：</span>
                    </el-form-item>
                    <el-form-item>
                      <el-select
                        v-model="contractForm.counterSignUsers"
                        multiple
                        filterable
                        remote
                        reserve-keyword
                        placeholder="请输入用户名搜索"
                        :remote-method="handleCounterSignUserSearch"
                        :loading="counterSignUsersLoading"
                        style="width: 220px"
                        :remote-show-suffix="true"
                        @visible-change="handleCounterSignUserVisibleChange"
                      >
                        <div
                          style="max-height: 200px; overflow-y: auto"
                          @scroll.passive="handleCounterSignUserScroll"
                        >
                          <el-option
                            v-for="item in counterSignUsers"
                            :key="item.userId"
                            :label="item.nickName"
                            :value="item.userId"
                          />
                        </div>
                      </el-select>
                    </el-form-item>
                    <el-form-item>
                      <span style="color: red; margin-right: 5px">*</span>
                      <el-button
                        type="primary"
                        @click="saveSealData('虚拟')"
                        :disabled="
                          (contractForm.approvalNo ? true : false) &&
                          (contractForm.id ? true : false)
                        "
                      >
                        发起飞书预审流程
                      </el-button>
                      <div
                        v-if="contractForm.approvalNo"
                        style="color: red; position: absolute; top: 35px; left: 0"
                      >
                        已创建飞书流程，当前状态：{{
                          contractForm.approvalStatus == "ERROR"
                            ? "创建失败"
                            : contractForm.approvalStatus == "PENDING"
                            ? "审批中"
                            : "通过"
                        }}
                      </div>
                    </el-form-item>
                    <el-form-item label="">
                      <el-upload
                        class="upload-demo"
                        :show-file-list="true"
                        :auto-upload="true"
                        :file-list="fileListVirtualArchive"
                        :before-upload="(file) => beforeUpload(file, 14)"
                        :on-change="(f, fl) => handleFileChange('virtualArchive', f, fl)"
                        :on-preview="(file) => handleFilePreview(file, 'virtualArchive')"
                        :on-remove="(file) => handleFileRemove('virtualArchive', file)"
                        :multiple="true"
                        accept="application/pdf,image/*"
                        list-type="text"
                        ><span style="color: red; margin-right: 5px">*</span>
                        <el-button
                          :disabled="contractForm.id ? false : true"
                          type="primary"
                        >
                          上传虚拟合同归档文件
                        </el-button>
                      </el-upload>
                    </el-form-item>
                  </el-form>
                </el-card>
              </div>
              <!-- 合同环节操作按钮 -->
              <div
                style="
                  margin-top: 32px;
                  margin-bottom: 60px;
                  display: flex;
                  gap: 16px;
                  flex-wrap: wrap;
                "
              >
                <el-button @click="handlePrevStep" :disabled="activeStep === 0" plain>
                  上一步
                </el-button>

                <el-button
                  @click="handleNextStep"
                  v-if="!shouldShowCompleteContractButton"
                  :disabled="activeStep === steps.length - 1"
                  plain
                >
                  下一步
                </el-button>

                <el-button
                  :disabled="!shouldShowCompleteContractButton"
                  v-if="shouldShowCompleteContractButton"
                  type="success"
                  @click="handleCompleteRecordStep('合同')"
                >
                  完成合同
                </el-button>
              </div>
            </div>
          </div>
          <!-- 办证环节 -->
          <div v-show="activeStep === 2" class="property-content">
            <el-card class="material-block" style="margin-top: 18px" shadow="never">
              <div class="block-title">
                办证模块
                <el-icon
                  class="tip-icon"
                  @click="handleFilePreview(banzhengliuch, '示例图')"
                >
                  <QuestionFilled />
                </el-icon>
                <span class="tip-text" @click="handleFilePreview(banzhengliuch, '示例图')"
                  >办证流程</span
                >
              </div>
              <div class="material-inner-row">
                <div class="upload-vertical">
                  <div class="upload-section">
                    <div class="upload-label">法人签字笔迹</div>
                    <el-upload
                      class="upload-demo"
                      :show-file-list="true"
                      :auto-upload="true"
                      :file-list="fileListSign"
                      :before-upload="(file) => beforeUpload(file, 2)"
                      :on-change="(f, fl) => handleFileChange('sign', f, fl)"
                      :on-preview="(file) => handleFilePreview(file, 'sign')"
                      :on-remove="(file) => handleFileRemove('sign', file)"
                      :multiple="true"
                      accept="image/*"
                    >
                      <el-button type="primary">上传法人签字笔迹</el-button>
                    </el-upload>
                  </div>
                  <div class="upload-section">
                    <div class="upload-label">自然人身份证</div>
                    <el-upload
                      class="upload-demo"
                      :show-file-list="true"
                      :auto-upload="true"
                      :file-list="fileListId"
                      :before-upload="(file) => beforeUpload(file, 3)"
                      :on-change="(f, fl) => handleFileChange('id', f, fl)"
                      :on-preview="(file) => handleFilePreview(file, 'id')"
                      :on-remove="(file) => handleFileRemove('id', file)"
                      :multiple="true"
                      accept="image/*"
                    >
                      <el-button type="primary">上传自然人身份证</el-button>
                    </el-upload>
                  </div>
                  <div class="upload-section">
                    <div class="upload-label">非自然人营业执照</div>
                    <el-upload
                      class="upload-demo"
                      :show-file-list="true"
                      :auto-upload="true"
                      :file-list="fileListLicense"
                      :before-upload="(file) => beforeUpload(file, 4)"
                      :on-change="(f, fl) => handleFileChange('license', f, fl)"
                      :on-preview="(file) => handleFilePreview(file, 'license')"
                      :on-remove="(file) => handleFileRemove('license', file)"
                      :multiple="true"
                      accept="image/*"
                    >
                      <el-button type="primary">上传非自然人营业执照</el-button>
                    </el-upload>
                  </div>
                  <div class="upload-section">
                    <div class="upload-label">营业执照</div>
                    <el-upload
                      class="upload-demo"
                      :show-file-list="true"
                      :auto-upload="true"
                      :file-list="fileListLicensePdf"
                      :before-upload="(file) => beforeUpload(file, 12)"
                      :on-change="(f, fl) => handleFileChange('licensePdf', f, fl)"
                      :on-preview="(file) => handleFilePreview(file, 'licensePdf')"
                      :on-remove="(file) => handleFileRemove('licensePdf', file)"
                      accept="*"
                      list-type="text"
                    >
                      <el-button type="primary">上传营业执照</el-button>
                    </el-upload>
                  </div>
                </div>
                <div class="block-img"></div>
              </div>
            </el-card>

            <!-- 在办证环节的末尾添加操作按钮 -->
            <div style="margin-top: 32px; margin-bottom: 60px; display: flex; gap: 16px">
              <el-button @click="handlePrevStep" :disabled="activeStep === 0"
                >上一步</el-button
              >

              <el-button
                @click="handleNextStep"
                v-if="!shouldShowCompletePropertyButton"
                :disabled="activeStep === steps.length - 1"
              >
                下一步
              </el-button>

              <el-button
                :diabled="!shouldShowCompletePropertyButton"
                v-if="shouldShowCompletePropertyButton"
                type="success"
                @click="handleCompletePropertyStep"
              >
                完成当前模块
              </el-button>
            </div>
          </div>
          <!-- 在模板中添加入驻告知步骤的内容 -->

          <!-- 在模板中添加入驻告知步骤的内容 -->
          <div v-show="activeStep === 3" class="notice-content">
            <div class="notice-header">
              <h2>企业入驻告知书</h2>
              <p>欢迎入驻苏州数字健康产业园</p>
            </div>

            <!-- 轮播图 -->
            <div class="carousel-container">
              <el-carousel :interval="3000" indicator-position="outside" height="300px">
                <el-carousel-item
                  v-for="(image, index) in noticeContent.parkInfo.carouselImages"
                  :key="index"
                >
                  <img
                    :src="image"
                    alt="园区环境"
                    style="width: 100%; height: 100%; object-fit: cover"
                  />
                </el-carousel-item>
              </el-carousel>
            </div>

            <!-- 标签 -->
            <div class="tags-container">
              <h3>园区标签</h3>
              <div class="tags">
                <span v-for="tag in noticeContent.parkInfo.tags" :key="tag" class="tag">{{
                  tag
                }}</span>
              </div>
            </div>

            <!-- 园区介绍 -->
            <div class="park-introduction">
              <h3>园区介绍</h3>
              <p>{{ noticeContent.parkInfo.introduction }}</p>
            </div>

            <!-- 服务时间节点 -->
            <div class="service-timeline" v-if="serviceTimeline.length > 0">
              <h3>服务时间节点</h3>
              <el-timeline>
                <el-timeline-item
                  v-for="(item, index) in serviceTimeline"
                  :key="index"
                  :timestamp="item.timestamp"
                  :type="item.type"
                  placement="top"
                >
                  {{ item.content }}
                </el-timeline-item>
              </el-timeline>
            </div>

            <!-- 服务清单 -->
            <div class="services-list">
              <h3>园区服务清单</h3>
              <el-table :data="noticeContent.services" border style="width: 100%">
                <el-table-column
                  prop="category"
                  label="服务类别"
                  width="180"
                ></el-table-column>
                <el-table-column label="服务内容">
                  <template #default="scope">
                    <table class="service-items-table">
                      <tbody>
                        <tr v-for="(item, index) in scope.row.items" :key="index">
                          <td>{{ item }}</td>
                        </tr>
                      </tbody>
                    </table>
                  </template>
                </el-table-column>
              </el-table>
            </div>

            <!-- 生成按钮 -->
            <div class="generate-button">
              <el-button @click="handlePrevStep" :disabled="activeStep === 0"
                >上一步</el-button
              >
              <el-button type="primary" @click="generateNoticePdf"
                >生成企业入驻告知书</el-button
              >
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 文件预览弹窗 -->
    <el-dialog
      v-model="previewDialogVisible"
      :title="'文件预览：' + previewFileName"
      width="60vw"
      top="5vh"
      :close-on-click-modal="false"
    >
      <template v-if="previewFileType === 'image'">
        <img :src="previewFileUrl" alt="" style="width: 55vw" />
      </template>
      <template v-else-if="previewFileType === 'pdf'">
        <iframe :src="previewFileUrl" style="width: 100%; height: 70vh; border: none" />
      </template>
      <template v-else-if="previewFileType === 'word'">
        <iframe
          :src="
            'https://view.officeapps.live.com/op/view.aspx?src=' +
            encodeURIComponent(previewFileUrl)
          "
          style="width: 100%; height: 70vh; border: none"
        />
      </template>
      <template v-else-if="previewFileType === 'excel'">
        <iframe
          :src="
            'https://view.officeapps.live.com/op/view.aspx?src=' +
            encodeURIComponent(previewFileUrl)
          "
          style="width: 100%; height: 70vh; border: none"
        />
      </template>
      <template v-else>
        <el-alert
          type="warning"
          :closable="false"
          title="暂不支持此类型文件在线预览，可下载后本地打开。"
        />
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
// 新增：付款方式数字输入
const payNum = ref("1");
const depositNum = ref("1");
// 新增：租赁期限日期和年限
const leaseDateRange = ref([]); // [start, end]
const leaseDateRange_start = ref("");
const leaseYears = ref("");
import html2pdf from "html2pdf.js";

import { onMounted, ref, watch, computed, getCurrentInstance } from "vue";
import { ArrowLeft, QuestionFilled } from "@element-plus/icons-vue";
import wuyeLcshouc from "../../assets/wuye_lcshouc.png";

import id_example_test from "../../assets/id-example.png";
import licenseExample from "../../assets/license-example.png";
import picuat1 from "../../assets/图片1.jpg";
import picuat2 from "../../assets/图片2.jpg";
import picuat3 from "../../assets/图片3.jpg";
import picuat4 from "../../assets/图片4.jpg";

import { getCarrierInfo } from "../../api/company";

import { generateContractNumber } from "@/api/company/index.js"; //

import {
  getFileByCompanyIdAndTag,
  companyUploadFile,
  deleteFile,
  getDraftContract,
  createDraftContract,
  updateDraftContract,
  submitAndUpdate,
  rentRoom,
} from "@/api/company/index.js";
import {
  insertCertification,
  createFeiShuApprovalTask,
  listForUser,
} from "@/api/company/info.js";
import { ElImageViewer, ElMessage, ElLoading } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import { submitFeiShuApproval } from "@/api/company/index.js"; // 提交飞书审批
import { generateWord } from "@/api/company/index.js"; //
import banzhengliuch from "@/assets/banzhengliuch.png";

import { updateCertification } from "@/api/certificate/index.js";
import {
  getPaymentPlanList,
  addPaymentPlan,
  updatePaymentPlan,
} from "@/api/company/index.js"; // 回款计划表格数据
import { bindRoom } from "@/api/property/index.js"; // 绑定房间号
// 获取所有房源列表
import { getAllRoomList } from "@/api/property/index";
// 计算属性：判断是否可以生成PDF
const canGeneratePdf = computed(() => {
  return (
    fileListBeforeDecoration.value.length > 0 && fileListAfterDecoration.value.length > 0
  );
});
// 在组件顶部添加新的数据和方法
const noticeContent = ref({
  services: [
    { category: "基础服务", items: ["工商注册代办", "银行开户对接", "装修"] },
    {
      category: "基础服务",
      items: [
        "工商注册、变更，注销，解异等",
        "税务开户、变更、注销、解异等",
        "社保、公积金开户、参保、退工、注销等",
        "银行开户对接",
      ],
    },
    {
      category: "基础服务",
      items: [
        "证照办理（食品经营许可证、道路运输许可证、劳务派遣许可证、二类医疗器械备案和三类经营许可证等）",
      ],
    },
    { category: "基础服务", items: ["装修"] },
    {
      category: "配套服务",
      items: ["人才公寓申请", "空间共享（会议室、青澜会客厅等）"],
    },
    {
      category: "科技服务",
      items: [
        "产学研对接",
        "知识产权规划",
        "领军人才政策申报（排摸项目源、匹配申报条件、协助材料准备）",
        "科技型中小企业、省民营科技企业、高新技术企业、专精特新企业等资质申报",
      ],
    },
    {
      category: "政策服务",
      items: ["政策梳理与宣贯", "租房、安家、一次性创业、社保等各类补贴申请全流程代办"],
    },
    { category: "金融服务", items: ["股权融资", "债权融资"] },
    {
      category: "人才服务",
      items: [
        "人才招聘服务",
        "人才乐居补贴申请代办",
        "领军人才政策申报（排摸项目源、匹配申报条件、协助材料准备）",
      ],
    },
    {
      category: "市场服务",
      items: ["政企场景对接", "企业家健康中心/西山健康基地", "海外资源对接（出海服务）"],
    },
    { category: "产业服务", items: [] },
  ],
  parkInfo: {
    carouselImages: [picuat1, picuat2, picuat3, picuat4],
    tags: ["大健康", "活力岛", "地铁4号线", "精装", "停车场", "功能配套齐全"],
    introduction: `苏州数字健康产业园位于苏州市相城区元和街道聚茂街185号活力商务广场B幢，总面积达2.7万方，单层面积1450㎡左右。园区以数字化诊断为主导方向，辅以数字化保健与数字化医药，重点打造“1+1+1”的产业发展模式，是集项目孵化、政策申报、投融资、技术与资源支持等多种服务于一体的孵化科创载体。

目前园区孵化器苏州数字健康科创园已获评国家级科技企业孵化器、省级科技企业孵化器、省级创业示范基地、23年获评苏州市招商运营成绩突出楼宇，24年获评苏州市综合评价优秀楼宇等荣誉资质。连续两年在市级创业孵化基地绩效考核中评定A级创业孵化基地。园区众创空间澜空间·云翼已获批区市省级众创空间。`,
    address: "位于苏州市相城区元和街道聚茂街185号活力商务广场B幢",
    transportation: `地处苏州城北核心区域、长江三角洲掌心。苏州城市轨交四号线活力岛地铁站号出口200米，邻近中环快速路，距离苏州站4.9km、距离苏州北站6.8km、距离苏南硕放国际机场32km、上海虹桥国际机场85km、上海浦东国际机场142km、南京禄口国际机场196km。`,
    facilities: `距离汇萃人才公寓步行5分钟，临近美好荟、活力东岛、繁花中心、大悦城等多样商业综合体。`,
  },
});
// 生成企业入驻告知书PDF
async function generateNoticePdf() {
  const loadingInstance = ElLoading.service({
    lock: true,
    text: "正在生成企业入驻告知书...",
    background: "rgba(0, 0, 0, 0.7)",
    spinner: "el-icon-loading",
    target: document.body,
  });

  try {
    const container = document.createElement("div");
    container.style.padding = "30px";
    container.style.fontFamily = "Arial, sans-serif";
    container.style.fontSize = "14px";

    // 第一页：标题和园区信息
    let htmlContent = `
      <h1 style="text-align: center; color: #000; font-size: 24px;">企业入驻告知书</h1>
      
      
      <div>
        <h3 style="color: #000;">致${getPersistedParam("companyName")}:</h2> 
      </div>
      <div style="margin: 30px 0; text-align: center;">
        <h3>苏州数字健康产业园-联健元和-园区标签</h3>
        <div style="display: flex; justify-content: center; gap: 10px; margin-top: 10px;">
          ${noticeContent.value.parkInfo.tags
            .map(
              (tag) =>
                `<span style="background-color: #e6f7ff; color: #0066cc; padding: 5px 10px; border-radius: 15px; font-size: 14px;">${tag}</span>`
            )
            .join("")}
        </div>
      </div>
      
      <div style="margin: 30px 0;">
        <h3>园区介绍</h3>
        <p>${noticeContent.value.parkInfo.introduction}</p>
      </div>
      
      <div style="margin: 30px 0;">
        <h3>园区地址</h3>
        <p>${noticeContent.value.parkInfo.address}</p>
      </div>
      
      <div style="margin: 30rne 0;">
        <h3>区位交通</h3>
        <p>${noticeContent.value.parkInfo.transportation}</p>
      </div>
      
      <div style="margin: 30px 0;">
        <h3>周边配套</h3>
        <p>${noticeContent.value.parkInfo.facilities}</p>
      </div>
    `;

    // 添加服务清单
    htmlContent += `
      <!-- 分页符 -->
      <div style="page-break-after: always;"></div>
      
      <div style="margin: 30px 0;">
        <h2 style="text-align: center; color: #000;">园区服务清单</h2>
      </div>
      
      <div style="margin: 30px 0;">
        <table style="width: 100%; border-collapse: collapse;">
          ${noticeContent.value.services
            .map(
              (service) => `
            <tr>
              <td style="border: 1px solid #000; padding: 8px; background-color: #f0f0f0; font-weight: bold;">${
                service.category
              }</td>
            </tr>
            ${service.items
              .map(
                (item) => `
              <tr>
                <td style="border: 1px solid #000; padding: 8px; text-indent: 20px;">${item}</td>
              </tr>
            `
              )
              .join("")}
          `
            )
            .join("")}
        </table>
      </div>
    `;

    container.innerHTML = htmlContent;

    document.body.appendChild(container);

    const options = {
      margin: [10, 10, 10, 10],
      filename: "企业入驻告知书.pdf",
      html2canvas: { scale: 2 },
      jsPDF: { unit: "mm", format: "a4", orientation: "portrait" },
    };

    html2pdf().from(container).set(options).save();

    document.body.removeChild(container);
  } catch (error) {
    console.error("PDF 生成失败:", error);
    proxy.$modal.msgWarning("网络繁忙, 请稍后重试");
  } finally {
    loadingInstance.close();
  }
}

// 生成合同编号
async function handleGenerateContractNumber() {
  const companyId = contractForm.value.companyId;
  if (!companyId) {
    proxy.$modal.msgWarning("请先选择公司");
    return;
  }
  try {
    const res = await generateContractNumber({ companyId });
    if (res && res.data) {
      contractForm.value.contractNumber = res.data;
      proxy.$modal.msgSuccess("合同编号生成成功");
    } else {
      proxy.$modal.msgError("合同编号生成失败");
    }
  } catch (e) {
    console.error("生成合同编号失败:", e);
  }
}
const { proxy } = getCurrentInstance();

// 返回上一页
function handleGoBack() {
  router.back();
}

const fileListRecord = ref([]); // 备案情况说明
const fileListRecordOk = ref([]); // 备案回执
const fileListInfo = ref([]); // 信息注册表
const fileListSign = ref([]); // 法人签字笔迹
const fileListId = ref([]); // 自然人身份证
const fileListLicense = ref([]); // 营业执照
const uploading = ref([false, false, false, false, false]);
const activeStep = ref(0);
const route = useRoute();
const router = useRouter();
// 注册类型持久化
const companyClass = ref("");
// 合同类型Tab
const contractType = ref("虚拟");
// 合同拟定表单数据
const contractForm = ref({
  type: contractType.value,
  companyId: route.query.companyId || route.params.companyId || "",
  contractNumber: "",
  carrierName: "",

  carrierInfo: {
    lessorName: "",
    lessorContactPerson: "",
    lessorContactInfo: "",
    lessorCreditCode: "",
    lessorAddress: "",
    lessorBank: "",
    lessorAccount: "",
  },
  lesseeName: "",
  lesseeContactPerson: "",
  lesseeContactInfo: "",
  lesseeCreditCode: "",
  lesseeAddress: "",
  lesseeBank: "",
  lesseeAccount: "",
  address: "",
  roomNumber: [],
  roomId: "",
  area: "",
  leaseTerm: "",
  rentFreePeriod: "",
  unitRentPrice: "",
  propertyType: "",
  paymentTerms: "",
  securityDeposit: "",
  amount: "", // 物业费/金额
  // accelerator专有
  waterExpense: "",
  electricityExpense: "",
  level: "",
  // 虚拟专有
  year: "",
  message: "",
  lessorName: "", // 虚拟专有
});

// 空闲房号
const freeRooms = ref([]);
// 获取房间状态文本
function getRoomStatusText(status) {
  const statusMap = {
    0: "未出租",
    1: "占用中",
    2: "已出租",
  };
  return statusMap[status] || "未知";
}

// 判断房间是否属于当前合同
function isRoomBelongsToContract(roomId) {
  if (!contractForm.value.roomId) return false;
  const contractRoomIds = contractForm.value.roomId.split(",").filter((id) => id);
  return contractRoomIds.includes(String(roomId));
}

// 判断房间是否应该禁用
function isRoomDisabled(item) {
  // 如果状态为0（未出租），不禁用
  if (item.status === 0) return false;
  // 如果状态不为0但房间属于当前合同，不禁用
  if (isRoomBelongsToContract(item.id)) return false;
  // 其他情况（状态不为0且不属于当前合同），禁用
  return true;
}

async function fetchFreeRooms() {
  try {
    const params = {
      contractNumber: contractForm.value.contractNumber,
      zt: route.query.zt,
    };
    const res = await getAllRoomList(params);
    freeRooms.value = res && res.rows ? res.rows : [];
  } catch (e) {
    freeRooms.value = [];
  }
}

// 导入更新资产接口
import { getPropertyList, addProperty, updateProperty } from "@/api/company/index.js";

// ... existing code ...

// 资产清单相关数据
const propertyList = ref([]); // 资产清单列表
const propertyForm = ref({
  type: "",
  number: 1,
  remake: "",
});
const propertyDialogVisible = ref(false);
const editPropertyRow = ref(-1); // 当前编辑的资产行索引
const addPropertyRowVisible = ref(false); // 是否正在添加新资产行
const editPropertyForm = ref({}); // 编辑表单数据

const propertyTypes = [
  "工位",
  "老板桌",
  "办公椅",
  "沙发",
  "茶几",
  "空调遥控器",
  "钥匙",
  "门禁",
  "空调",
  "灯",
  "隔断",
  "地毯",
  "地板",
  "其他",
];

// 获取资产清单数据
async function fetchPropertyList() {
  const companyId = route.query.companyId || route.params.companyId;
  if (!companyId) return;

  try {
    const res = await getPropertyList({
      companyId,
      pageNum: 1,
      pageSize: 100,
    });
    propertyList.value = res && res.rows ? res.rows : [];
  } catch (e) {
    console.error("获取资产清单失败:", e);
  }
}

// 添加资产清单项
function handleAddProperty() {
  addPropertyRowVisible.value = true;
  editPropertyRow.value = propertyList.value.length;
  editPropertyForm.value = {
    type: "",
    number: 1,
    remake: "",
  };
  propertyList.value.push({ ...editPropertyForm.value });
}

// 编辑资产清单项
function handleEditProperty(index, row) {
  editPropertyRow.value = index;
  addPropertyRowVisible.value = false;
  editPropertyForm.value = { ...row };
}

// 取消编辑资产清单项
function handleCancelEditProperty() {
  if (addPropertyRowVisible.value) propertyList.value.pop();
  editPropertyRow.value = -1;
  addPropertyRowVisible.value = false;
}

// 保存资产清单项
async function handleSaveProperty() {
  const companyId = route.query.companyId || route.params.companyId;
  if (!companyId) {
    proxy.$modal.msgWarning("缺少公司ID");
    return;
  }

  if (!editPropertyForm.value.type) {
    proxy.$modal.msgWarning("请选择资产类型");
    return;
  }

  if (!editPropertyForm.value.number || editPropertyForm.value.number <= 0) {
    proxy.$modal.msgWarning("请输入有效的资产数量");
    return;
  }

  try {
    let res;
    // 如果有id，则是更新，否则是新增
    if (editPropertyForm.value.id) {
      res = await updateProperty({
        ...editPropertyForm.value,
        companyId,
        flag: 0,
      });
    } else {
      res = await addProperty({
        companyId,
        type: editPropertyForm.value.type,
        number: editPropertyForm.value.number,
        remake: editPropertyForm.value.remake,
      });
    }

    if (res.code === 200) {
      proxy.$modal.msgSuccess("保存成功");
      editPropertyRow.value = -1;
      addPropertyRowVisible.value = false;
      fetchPropertyList(); // 重新获取列表
    } else {
      proxy.$modal.msgError(res.msg || "保存失败");
    }
  } catch (e) {
    console.error("保存资产失败:", e);
  }
}

// 打开添加资产对话框（用于弹窗方式添加）
function openAddPropertyDialog() {
  propertyForm.value = { type: "", number: 1, remake: "" };
  propertyDialogVisible.value = true;
}

// 添加资产（弹窗方式）
async function addPropertyItem() {
  const companyId = route.query.companyId || route.params.companyId;
  if (!companyId) {
    proxy.$modal.msgWarning("缺少公司ID");
    return;
  }

  if (!propertyForm.value.type) {
    proxy.$modal.msgWarning("请选择资产类型");
    return;
  }

  if (!propertyForm.value.number || propertyForm.value.number <= 0) {
    proxy.$modal.msgWarning("请输入有效的资产数量");
    return;
  }

  try {
    const res = await addProperty({
      companyId,
      type: propertyForm.value.type,
      number: propertyForm.value.number,
      remake: propertyForm.value.remake,
    });

    if (res.code === 200) {
      proxy.$modal.msgSuccess("添加成功");
      propertyDialogVisible.value = false;
      propertyForm.value = { type: "", number: 1, remake: "" };
      fetchPropertyList(); // 重新获取列表
    } else {
      proxy.$modal.msgError(res.msg || "添加失败");
    }
  } catch (e) {
    console.error("添加资产失败:", e);
  }
}

// 在生成物业交接单前检查资产清单
async function checkPropertyListBeforeGenerate() {
  await fetchPropertyList();
  if (!propertyList.value || propertyList.value.length === 0) {
    proxy.$modal
      .confirm("尚未添加资产清单，是否现在添加？", "提示", {
        confirmButtonText: "添加资产",
        cancelButtonText: "取消",
        type: "warning",
      })
      .then(() => {
        openAddPropertyDialog();
        return false;
      })
      .catch(() => {
        return false;
      });
    return false;
  }
  return true;
}
// 工具函数：将图片 URL 转为 base64
const toBase64 = (url) => {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.crossOrigin = "anonymous"; // 必须加，否则报错
    img.onload = () => {
      const canvas = document.createElement("canvas");
      const ctx = canvas.getContext("2d");
      canvas.width = img.width;
      canvas.height = img.height;
      ctx.drawImage(img, 0, 0);
      resolve(canvas.toDataURL("image/png")); // 输出 PNG base64
    };
    img.onerror = reject;
    img.src = url;
  });
};

// Tab切换时同步type
function handleTabChange(tab) {
  contractType.value = tab.paneName;
  contractForm.value.type = contractType.value;
  // 清空表单数据
  contractForm.value = {
    type: contractType.value,
    companyId: route.query.companyId || route.params.companyId || "",
    contractNumber: "",
    carrierName: "",

    carrierInfo: {
      lessorName: "",
      lessorContactPerson: "",
      lessorContactInfo: "",
      lessorCreditCode: "",
      lessorAddress: "",
      lessorBank: "",
      lessorAccount: "",
    },
    lesseeName: "",
    lesseeContactPerson: "",
    lesseeContactInfo: "",
    lesseeCreditCode: "",
    lesseeAddress: "",
    lesseeBank: "",
    lesseeAccount: "",
    address: "",
    roomNumber: [],
    roomId: "",
    area: "",
    leaseTerm: "",
    rentFreePeriod: "",
    unitRentPrice: "",
    propertyType: "自有物业",
    paymentTerms: "",
    securityDeposit: "",
    amount: "", // 物业费/金额
    // accelerator专有
    waterExpense: "",
    electricityExpense: "",
    level: "",
    // 虚拟专有
    year: "",
    message: "",
    lessorName: "", // 虚拟专有
  };
  getCarrierInfoData(); // 切换时重新获取草稿合同
  // 在 tab 切换时调用飞书审批任务信息接口
  if (contractForm.value.contractNumber) {
    fetchFeiShuApprovalTaskMessage();
  }
}
// 添加获取飞书审批任务信息的函数
async function fetchFeiShuApprovalTaskMessage() {
  if (!contractForm.value.contractNumber) {
    console.log("缺少合同编号，无法获取审批任务信息");
    return;
  }

  try {
    // 根据合同类型确定 approvalType
    const approvalType = contractType.value === "虚拟" ? "虚拟" : "实体";

    const res = await getFeiShuApprovalTaskMessage({
      contractNumber: contractForm.value.contractNumber,
      approvalType: approvalType,
      companyId: route.query.companyId || route.params.companyId,
    });

    if (res && res.code === 200 && res.rows[0]) {
      sealTaskData.value = res.rows[0];

      // 如果有数据，禁用合同盖章归档模块的表单
      isContractSealDisabled.value = true;

      // 回显合同盖章归档的数据
      if (contractType.value === "虚拟") {
        // 虚拟合同回显
        sealVirtualType.value = res.rows[0].sealType || "实体章";
        approvalVirtualNumber.value = res.rows[0].approvalNo || "";
        createTimeVirtual.value = res.rows[0].createTime || new Date();
      } else {
        // 实体合同回显
        sealType.value = res.rows[0].sealType || "实体章";
        approvalNumber.value = res.rows[0].approvalNo || "";
        createTimeSeal.value = res.rows[0].createTime || new Date();
      }
    } else {
      // 没有数据，启用表单
      isContractSealDisabled.value = false;
      sealTaskData.value = null;
    }
  } catch (e) {
    console.error("获取飞书审批任务信息失败:", e);
    // 出错时启用表单
    isContractSealDisabled.value = false;
    sealTaskData.value = null;
  }
}
const contractFormRef = ref();
const contractRules = {
  contractNumber: [{ required: true, message: "合同编号必填", trigger: "blur" }],
  lessorName: [],
  lessorContactPerson: [],
  lessorContactInfo: [],
  lessorCreditCode: [],
  lessorAddress: [],
  lessorBank: [],
  lessorAccount: [],
  lesseeName: [],
  lesseeContactPerson: [{ required: true, message: "承租方联系人必填", trigger: "blur" }],
  lesseeContactInfo: [{ required: true, message: "承租方联系方式必填", trigger: "blur" }],
  lesseeCreditCode: [],
  lesseeAddress: [],
  lesseeBank: [],
  lesseeAccount: [],
  address: [{ required: true, message: "项目地址必填", trigger: "blur" }],
  roomNumber: [
    { required: true, message: "房号必填", trigger: "change", type: "array", min: 1 },
  ],
  area: [{ required: true, message: "面积必填", trigger: "blur" }],
  leaseTerm: [
    {
      required: true,
      message: "租赁期限必填",
      trigger: "blur",
      validator: (rule, value, callback) => {
        callback();
      },
    },
  ],
  unitRentPrice: [{ required: true, message: "租金单价必填", trigger: "blur" }],
  propertyType: [{ required: true, message: "物业类型必填", trigger: "change" }],
  paymentTerms: [],
  securityDeposit: [{ required: true, message: "保证金必填", trigger: "blur" }],
  amount: [
    {
      required: true,
      message: "物业费必填",
      trigger: "blur",
      validator: (rule, value, callback) => {
        if (
          contractForm.value.propertyType === "自有物业" &&
          (!value || isNaN(Number(value)) || Number(value) < 0)
        ) {
          callback(new Error("请输入有效的物业费"));
        } else {
          callback();
        }
      },
    },
  ],
};
// 服务时间节点数据
const serviceTimeline = ref([]);

// 获取服务时间节点数据
async function fetchServiceTimeline() {
  try {
    const companyId = route.query.companyId || route.params.companyId;
    if (!companyId) return;

    const res = await getServingNode({ companyId });
    if (res.code === 200 && res.data) {
      const timelineData = [];

      // 处理政府备案时间
      if (res.data["政府备案开始时间"]) {
        timelineData.push({
          content: "政府备案开始",
          timestamp: res.data["政府备案开始时间"],
          type: "primary",
        });
      }

      if (res.data["政府备案结束时间"]) {
        timelineData.push({
          content: "政府备案结束",
          timestamp: res.data["政府备案结束时间"],
          type: "success",
        });
      }

      // 处理合同拟定时间
      if (res.data["合同拟定开始时间"]) {
        timelineData.push({
          content: "合同拟定开始",
          timestamp: res.data["合同拟定开始时间"],
          type: "primary",
        });
      }

      if (res.data["合同拟定结束时间"]) {
        timelineData.push({
          content: "合同拟定结束",
          timestamp: res.data["合同拟定结束时间"],
          type: "success",
        });
      }

      // 处理办证时间
      if (res.data["办证开始时间"]) {
        timelineData.push({
          content: "办证开始",
          timestamp: res.data["办证开始时间"],
          type: "primary",
        });
      }

      if (res.data["办证结束时间"]) {
        timelineData.push({
          content: "办证结束",
          timestamp: res.data["办证结束时间"],
          type: "success",
        });
      }

      serviceTimeline.value = timelineData;
    }
  } catch (error) {
    console.error("获取服务时间节点失败:", error);
  }
}

// 合同归档文件
import { getFeiShuApprovalTaskMessage, getServingNode } from "@/api/company/index.js";

// 添加新的响应式数据
const isContractSealDisabled = ref(false); // 控制合同盖章归档表单是否禁用
const sealTaskData = ref(null); // 存储获取到的审批任务数据
const fileListContractArchive = ref([]);
const fileListVirtualArchive = ref([]);
const sealType = ref("实体章");
const sealVirtualType = ref("实体章");
const approvalVirtualNumber = ref("");
const approvalNumber = ref("");
// const createTime = ref(new Date()); // 创建日期
const createTimeSeal = ref(new Date()); // 实体创建日期
const createTimeVirtual = ref(new Date()); // 虚拟创建日期
// 会签人员相关数据
const counterSignUsers = ref([]);
const counterSignUsersLoading = ref(false);
const counterSignUserPage = ref(1);
const counterSignUserPageSize = ref(20);
const counterSignUserTotal = ref(0);
const counterSignUserSearch = ref("");
// 获取会签人员列表
const loadCounterSignUsers = async (reset = false) => {
  if (reset) {
    counterSignUserPage.value = 1;
    counterSignUsers.value = [];
  }

  counterSignUsersLoading.value = true;

  try {
    const params = {
      pageNum: counterSignUserPage.value,
      pageSize: counterSignUserPageSize.value,
      nickName: counterSignUserSearch.value,
    };

    const response = await listForUser(params);
    const { rows, total } = response;

    if (reset) {
      counterSignUsers.value = rows;
    } else {
      counterSignUsers.value = [...counterSignUsers.value, ...rows];
    }

    counterSignUserTotal.value = total;
  } catch (error) {
    console.error("获取会签人员列表失败:", error);
  } finally {
    counterSignUsersLoading.value = false;
  }
};

// 防抖函数
const debounce = (func, wait) => {
  let timeout;
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout);
      func(...args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
};

// 搜索会签人员（带防抖）
const handleCounterSignUserSearch = debounce((query) => {
  counterSignUserSearch.value = query;
  loadCounterSignUsers(true);
}, 300);

// 滚动加载更多会签人员
const handleCounterSignUserScroll = (e) => {
  const { scrollTop, clientHeight, scrollHeight } = e.target;
  // 当滚动到底部且还有更多数据时加载更多
  if (scrollTop + clientHeight >= scrollHeight - 10 && !counterSignUsersLoading.value) {
    if (counterSignUsers.value.length < counterSignUserTotal.value) {
      counterSignUserPage.value++;
      loadCounterSignUsers();
    }
  }
};

// 当下拉框可见性改变时触发
const handleCounterSignUserVisibleChange = (visible) => {
  if (visible && counterSignUsers.value.length === 0) {
    // 当下拉框首次打开且还没有数据时加载数据
    loadCounterSignUsers(true);
  }
};

function saveSealData(type) {
  // const isVirtual = type === "虚拟";
  // const seal = isVirtual ? sealVirtualType.value : sealType.value;
  // const approvalNo = isVirtual ? approvalVirtualNumber.value : approvalNumber.value;
  // const approvalNoDate = isVirtual ? createTimeVirtual.value : createTimeSeal.value;
  // if (!approvalNo || !approvalNoDate) {
  //   proxy.$modal.msgError("请完善用印审批信息");
  //   return;
  // }
  // submitFeiShuApproval({
  //   type: "签章",
  //   contractNumber: contractForm.value.contractNumber,
  //   approvalType: type,
  //   sealType: seal,
  //   approvalNo: approvalNo,
  //   createTime: type == "实体" ? createTimeSeal.value : createTimeVirtual.value,
  //   // approvalNoDate: approvalNoDate, // 创建日期
  // })
  //   .then((res) => {
  //     proxy.$modal.msgSuccess("用印信息保存成功");
  //     fetchFeiShuApprovalTaskMessage(); // 保存后重新获取数据
  //   })
  //   .catch((err) => {
  //     proxy.$modal.msgError("用印信息保存失败，请稍后重试！");
  //   });
  createFeiShuApprovalTask({
    contractNumber: contractForm.value.contractNumber,
    // nickName: contractForm.value.counterSignUsers[0].nickName,
    userId: contractForm.value.counterSignUsers,
  }).then((res) => {
    proxy.$modal.msgSuccess("已创建飞书预审流程");
    fetchFeiShuApprovalTaskMessage(); // 保存后重新获取数据
    getCarrierInfoData();
  });
}
// 开票、物业、合同等步骤
const invoiceStart = ref("");
const invoiceStartTime = ref("");
function saveSealData_invoice() {
  if (!invoiceStart.value || !invoiceStartTime.value) {
    proxy.$modal.msgWarning("请完善开票流程信息");
    return;
  }
  submitFeiShuApproval({
    type: "开票",
    contractNumber: contractForm.value.contractNumber,

    approvalNo: invoiceStart.value,
    createTime: invoiceStartTime.value,
    // approv alNoDate: approvalNoDate, // 创建日期
  })
    .then((res) => {
      proxy.$modal.msgSuccess(" 开票流程信息保存成功");
    })
    .catch((err) => {
      console.error("开票流程信息保存失败:", err);
    });
}
const invoiceTaskData = ref(null); // 存储获取到的开票审批任务数据
const isInvoiceDisabled = ref(false); // 控制开票模块表单是否禁用
const approvalInvoiceNumber = ref(""); // 开票审批单号
const invoiceUrl = ref(""); // 开票审批链接
// 添加获取开票飞书审批任务信息的函数
async function fetchInvoiceFeiShuApprovalTaskMessage() {
  if (!contractForm.value.contractNumber || !route.query.companyId) {
    console.log("缺少合同编号或公司ID，无法获取开票审批任务信息");
    return;
  }

  try {
    const res = await getFeiShuApprovalTaskMessage({
      contractNumber: contractForm.value.contractNumber,
      approvalType: "开票",
      companyId: route.query.companyId,
    });

    if (res && res.code === 200 && res.rows[0]) {
      invoiceTaskData.value = res.rows[0];

      // 如果有数据，禁用开票模块表单
      isInvoiceDisabled.value = true;

      // 回显开票模块的数据
      invoiceStart.value = res.rows[0].startTime || "";
      invoiceStartTime.value = res.rows[0].createTime || "";
      approvalInvoiceNumber.value = res.rows[0].approvalNo || "";
      invoiceUrl.value = res.rows[0].url || "";
    } else {
      // 没有数据，启用表单
      isInvoiceDisabled.value = false;
      invoiceTaskData.value = null;
    }
  } catch (e) {
    console.error("获取开票飞书审批任务信息失败:", e);
    // 出错时启用表单
    isInvoiceDisabled.value = false;
    invoiceTaskData.value = null;
  }
}
// 信息保存按钮
function handleDraftContract() {
  contractFormRef.value.validate((valid) => {
    if (!valid) return;
    // 校验租赁期限和年限
    if (contractType.value === "虚拟") {
      if (!leaseDateRange_start.value) {
        proxy.$modal.msgWarning("请选择租赁期限");
        return;
      }
    } else {
      if (
        !leaseDateRange.value ||
        leaseDateRange.value.length !== 2 ||
        !leaseDateRange.value[0] ||
        !leaseDateRange.value[1]
      ) {
        proxy.$modal.msgWarning("请选择租赁期限");
        return;
      }
    }
    // 格式化日期为“YYYY年MM月DD日”
    function formatDateToCN(dateStr) {
      if (!dateStr) return "";
      const d = new Date(dateStr.replace(/-/g, "/"));
      const y = d.getFullYear();
      const m = d.getMonth() + 1;
      const day = d.getDate();
      return `${y}年${m}月${day}日`;
    }

    // 拼接 leaseTerm 字段 格式：自____年__月__日起至____年__月__日止，共计____年。
    if (contractType.value === "加速器") {
      const start = formatDateToCN(leaseDateRange.value[0]);

      const end = formatDateToCN(leaseDateRange.value[1]);

      contractForm.value.leaseTerm = `自${start}起至${end}止`;
    } else if (contractType.value === "孵化器") {
      const start = formatDateToCN(leaseDateRange.value[0]);

      const end = formatDateToCN(leaseDateRange.value[1]);

      contractForm.value.leaseTerm = `自${start}起至${end}止，共计${leaseYears.value}年。`;
    } else if (contractType.value === "虚拟") {
      const start = formatDateToCN(leaseDateRange_start.value);

      contractForm.value.leaseTerm = `该房屋租赁期${contractForm.value.year}年。自${start}起`;
    }
    // 拼接付款方式
    if (!payNum.value || isNaN(Number(payNum.value)) || Number(payNum.value) <= 0) {
      proxy.$modal.msgWarning("请输入有效的付款期数");
      return;
    }
    if (
      depositNum.value === "" ||
      isNaN(Number(depositNum.value)) ||
      Number(depositNum.value) < 0
    ) {
      proxy.$modal.msgWarning("请输入有效的押金期数");
      return;
    }
    contractForm.value.paymentTerms = `付${payNum.value}押${depositNum.value}`;
    // 移除房间号
    delete contractForm.value.roomNumber;
    console.log("信息保存数据：", contractForm.value);
    contractForm.value.type = contractType.value;
    if (contractForm.value.id) {
      // 已有草稿合同，更新
      updateDraftContract(contractForm.value)
        .then((res) => {
          proxy.$modal.msgSuccess("合同信息更新成功！");
          bindRoomNumber(contractForm.value); // 绑定房间号
          getCarrierInfoData(); // 保存后刷新数据，获取合同ID
        })
        .catch((err) => {
          console.error("合同信息更新失败:", err);
        });
      return;
    } else {
      // 新建草稿合同
      createDraftContract(contractForm.value)
        .then((res) => {
          proxy.$modal.msgSuccess("合同信息保存成功！");
          bindRoomNumber(contractForm.value); // 绑定房间号
          getCarrierInfoData(); // 保存后刷新数据，获取合同ID
        })
        .catch((err) => {
          console.error("合同信息保存失败:", err);
        });
    }
    // proxy.$modal.msgSuccess('合同信息校验通过，可进行后续操作！');
    // 此处可发起后端保存/生成合同等逻辑
  });
}

// 处理房号选择变化
function handleRoomChange(roomNumbers) {
  // 根据选择的房号数组找到对应的ID数组
  const selectedRoomIds = [];
  if (Array.isArray(roomNumbers)) {
    roomNumbers.forEach((roomNumber) => {
      const selectedRoom = freeRooms.value.find((room) => room.roomNumber === roomNumber);
      if (selectedRoom) {
        selectedRoomIds.push(selectedRoom.id);
      }
    });
  }
  // 用英文逗号拼接roomId
  contractForm.value.roomId = selectedRoomIds.join(",");
}

// 绑定房间号
function bindRoomNumber(data) {
  // 确保传递roomid给后端
  const bindData = {
    ...data,
    roomId: data.roomId,
  };
  bindRoom(bindData)
    .then((res) => {
      if (res.code !== 200) {
        proxy.$modal.msgError(res.msg || "房间号绑定失败");
      }
    })
    .catch((err) => {
      console.error("房间号绑定失败:", err);
    });
}

// 生成合同按钮
function handleCreatedDraftContract() {
  generateWord({ contractNumber: contractForm.value.contractNumber })
    .then((res) => {
      const link = document.createElement("a");
      link.href = res.data;
      link.setAttribute("download", `${contractForm.value.contractNumber}.docx`);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);

      proxy.$modal.msgSuccess("合同生成成功！");
    })
    .catch((err) => {
      console.log(err);
      // proxy.$modal.msgError("合同生成失败，请稍后重试！");
    });
}
const fileListBeforeDecoration = ref([]);
const fileListAfterDecoration = ref([]);
const fileListPropertyHandover = ref([]);
const fileListPlanPdf = ref([]);
const fileListPlanZip = ref([]);
const fileListWaterMeter = ref([]);
const fileListElectricMeter = ref([]);
const fileListLicensePdf = ref([]);
// 合同归档文件上传/预览/删除复用原有逻辑
function handleFileChange(type, file, fileListArr) {
  if (type === "record") fileListRecord.value = fileListArr;
  if (type === "record_ok") fileListRecordOk.value = fileListArr;

  if (type === "info") fileListInfo.value = fileListArr;
  if (type === "sign") fileListSign.value = fileListArr;
  if (type === "id") fileListId.value = fileListArr;
  if (type === "license") fileListLicense.value = fileListArr;
  if (type === "contractArchive") fileListContractArchive.value = fileListArr;
  if (type === "virtualArchive") fileListVirtualArchive.value = fileListArr;
  if (type === "beforeDecoration") fileListBeforeDecoration.value = fileListArr;
  if (type === "afterDecoration") fileListAfterDecoration.value = fileListArr;
  if (type === "propertyHandover") fileListPropertyHandover.value = fileListArr;
  if (type === "planPdf") fileListPlanPdf.value = fileListArr;
  if (type === "planZip") fileListPlanZip.value = fileListArr;
  if (type === "waterMeter") fileListWaterMeter.value = fileListArr;
  if (type === "electricMeter") fileListElectricMeter.value = fileListArr;
  if (type === "licensePdf") fileListLicensePdf.value = fileListArr;
}

// 合同归档文件回显
async function refreshFileListContractArchive() {
  const companyId = route.query.companyId || route.params.companyId;
  const params = {
    pageNum: 1,
    pageSize: 20,
    companyId,
    tag: 7,
  };
  // 先清空，避免el-upload混入本地临时文件
  fileListContractArchive.value = [];

  try {
    const res = await getFileByCompanyIdAndTag(params);
    // el-upload 需要的file-list格式：{name, url, status, uid}
    const files = (res && res.rows ? res.rows : []).map((f, idx) => ({
      id: f.id,
      name: f.name || "",
      url: f.url,
      status: "done",
      uid: f.id ? String(f.id) : String(Date.now()) + "_" + idx,
    }));
    fileListContractArchive.value = files;
  } catch (e) {
    // 可选：proxy.$modal.msgError("合同归档文件回显失败");
  }
}
// 合同归档文件回显
async function refreshFileListVirtualArchive() {
  const companyId = route.query.companyId || route.params.companyId;
  const params = {
    pageNum: 1,
    pageSize: 20,
    companyId,
    tag: 14,
  };
  // 先清空，避免el-upload混入本地临时文件
  fileListVirtualArchive.value = [];

  try {
    const res = await getFileByCompanyIdAndTag(params);
    // el-upload 需要的file-list格式：{name, url, status, uid}
    const files = (res && res.rows ? res.rows : []).map((f, idx) => ({
      id: f.id,
      name: f.name || "",
      url: f.url,
      status: "done",
      uid: f.id ? String(f.id) : String(Date.now()) + "_" + idx,
    }));
    fileListVirtualArchive.value = files;
  } catch (e) {
    // 可选：proxy.$modal.msgError("合同归档文件回显失败");
  }
}
async function getCarrierInfoData() {
  const companyId = route.query.companyId || route.params.companyId;
  const params = {
    companyId,
    type: contractType.value,
  };
  try {
    const { data } = await getDraftContract(params);
    if (data != null) {
      contractForm.value = { ...contractForm.value, ...data };
      // 处理房号回显，将字符串转换为数组
      if (data.roomNumber && typeof data.roomNumber === "string") {
        contractForm.value.roomNumber = data.roomNumber
          .split(",")
          .filter((item) => item.trim());
      } else if (data.roomNumber && Array.isArray(data.roomNumber)) {
        contractForm.value.roomNumber = data.roomNumber;
      }
      // 解析 paymentTerms（如"付3押1"）
      if (data.paymentTerms) {
        const payMatch = data.paymentTerms.match(/付(\d+)/);
        const depositMatch = data.paymentTerms.match(/押(\d+)/);
        payNum.value = payMatch ? payMatch[1] : "1";
        depositNum.value = depositMatch ? depositMatch[1] : "1";
      }
      // 解析 leaseTerm（如“自2025年9月1日起至2026年8月31日止，共计1年。”）
      if (data.leaseTerm) {
        // 匹配起止日期
        const dateMatch = data.leaseTerm.match(
          /自(\d{4}年\d{1,2}月\d{1,2}日)起至(\d{4}年\d{1,2}月\d{1,2}日)止/
        );
        if (dateMatch) {
          // 转换为 yyyy-mm-dd
          function cnDateToISO(str) {
            let Y = str.match(/(\d{4})年/);
            let M =
              str.match(/年(\d{1,2})月/) > 9
                ? str.match(/年(\d{1,2})月/)[1]
                : "0" + str.match(/年(\d{1,2})月/)[1];
            let D =
              str.match(/月(\d{1,2})日/) > 9
                ? str.match(/月(\d{1,2})日/)[1]
                : "0" + str.match(/月(\d{1,2})日/)[1];
            return `${Y[1]}-${M}-${D}`;
          }

          if (params.type != "虚拟") {
            leaseDateRange.value[0] = cnDateToISO(dateMatch[1]);
            leaseDateRange.value[1] = cnDateToISO(dateMatch[2]);
          } else {
            leaseDateRange_start.value = nDateToISO(dateMatch[1]);
          }
        }
        // 匹配年限
        let yearMatch = "";
        if (params.type === "孵化器") {
          yearMatch = data.leaseTerm.match(/共计(\d+)年/);
        } else if (params.type === "加速器") {
          yearMatch = data.leaseTerm.match(/共计(\d+)年/);
        } else if (params.type === "虚拟") {
          yearMatch = data.leaseTerm.match(/租赁期(\d+)年/);
        }
        console.log(yearMatch);
        leaseYears.value = yearMatch ? yearMatch[1] : "";
        contractForm.value.year = yearMatch ? yearMatch[1] : "";
        console.log("解析后的leaseDateRange:", leaseDateRange.value);
        console.log("解析后的leaseYears:", leaseYears.value);
      }
    } else {
      console.log("没有草稿合同，尝试从承租方信息接口获取承租方数据", data != null);
      const { data: carrierData } = await getCarrierInfo(params);
      // 如果没有草稿合同，尝试从承租方信息接口获取承租方数据
      if (carrierData) {
        contractForm.value.carrierInfo.lessorName = carrierData.lessorName || "";
        contractForm.value.carrierName = carrierData.carrierName || "";
        contractForm.value.carrierInfo.lessorContactPerson =
          carrierData.lessorContactPerson || "";
        contractForm.value.carrierInfo.lessorContactInfo =
          carrierData.lessorContactInfo || "";
        contractForm.value.carrierInfo.lessorCreditCode =
          carrierData.lessorCreditCode || "";
        contractForm.value.address = carrierData.lessorAddress || "";

        contractForm.value.carrierInfo.lessorAddress = carrierData.lessorAddress || "";
        contractForm.value.carrierInfo.lessorBank = carrierData.lessorBank || "";
        contractForm.value.carrierInfo.lessorAccount = carrierData.lessorAccount || "";
      }
    }
  } catch (e) {
    // 可选：proxy.$modal.msgError("获取出租方信息失败");
  }
}

watch(
  () => activeStep.value,
  (val) => {
    if (activeStep.value === 0) {
      console.log("step 0");
      // tag: 0-备案情况说明, 1-信息注册表, 2-法人签字笔迹, 3-身份证, 4-营业执照
      // 迁址只查tag=0，新注册查tag=0,1
      let tags = [0];
      if (companyClass.value !== "迁址") {
        tags.push(1);
      }
      tags = tags.concat([2, 3, 4]);
      tags.forEach(async (tag) => {
        const params = {
          pageNum: 1,
          pageSize: 20,
          companyId: route.query.companyId,
          tag,
        };
        try {
          const res = await getFileByCompanyIdAndTag(params);
          const files = (res && res.rows ? res.rows : []).map((f) => ({
            id: f.id,
            name: f.name || "",
            url: f.url,
          }));
          if (tag === 0) fileListRecord.value = files;
          else if (tag === 13) fileListRecordOk.value = files;
          else if (tag === 1) fileListInfo.value = files;
          else if (tag === 2) fileListSign.value = files;
          else if (tag === 3) fileListId.value = files;
          else if (tag === 4) fileListLicense.value = files;
        } catch (e) {
          // 可选： proxy.$modal.msgError("文件回显失败");
        }
      });
    }
    if (val === 1) {
      refreshFileListVirtualArchive();
      getCarrierInfoData();
      // 加载空闲房号
      fetchFreeRooms();
      // 第一次进入合同环节时调用飞书审批任务信息接口
      if (contractForm.value.contractNumber) {
        fetchFeiShuApprovalTaskMessage();
      }
    }
    if (activeStep.value === 2 && route.query.companyId) {
      // 初始化获取办证材料文件列表
      let tags = [2, 3, 4, 12]; // 法人签字笔迹、自然人身份证、非自然人营业执照、营业执照PDF
      tags.forEach(async (tag) => {
        const params = {
          pageNum: 1,
          pageSize: 20,
          companyId: route.query.companyId,
          tag,
        };
        try {
          const res = await getFileByCompanyIdAndTag(params);
          const files = (res && res.rows ? res.rows : []).map((f) => ({
            id: f.id,
            name: f.name || "",
            url: f.url,
          }));
          if (tag === 2) fileListSign.value = files;
          else if (tag === 3) fileListId.value = files;
          else if (tag === 4) fileListLicense.value = files;
          else if (tag === 12) fileListLicensePdf.value = files;
        } catch (e) {
          // 可选： proxy.$modal.msgError("文件回显失败");
        }
      });
    }
  }
);

// 读取companyClass等参数，优先路由，其次localStorage
// useRoute/useRouter已在顶部声明
function getPersistedParam(key, def = "") {
  return (
    route.query[key] ||
    route.params[key] ||
    localStorage.getItem("companyStep_" + key) ||
    def
  );
}

function persistParam(key, value) {
  console.log("Persisting param:", key, value);
  if (value !== undefined && value !== null) {
    localStorage.setItem("companyStep_" + key, value);
  }
}
// 步骤切换
// 文件预览弹窗相关
const previewDialogVisible = ref(false);
const previewFileType = ref("");
const previewFileUrl = ref("");
const previewFileName = ref("");

function handleFilePreview(file, type) {
  console.log("handleFilePreview", file, type);

  // file.url需为可访问的文件地址
  let url =
    type == "示例图"
      ? file
      : file.url ||
        file.response.data.url || // 添加对 response.data.url 的支持
        file.response.url ||
        file.preview ||
        (file.raw && URL.createObjectURL(file.raw)) ||
        "";

  // 确保 url 是字符串类型
  if (typeof url !== "string") {
    url = "";
  }

  if (!url) {
    proxy.$modal.msgWarning("文件地址无效");
    return;
  }

  previewFileUrl.value = url;
  previewFileName.value = file.name || file.fileName || "";

  // 判断文件类型
  const fileName =
    file.name ||
    file.fileName ||
    (typeof url === "string" ? url.split("/").pop() : "") ||
    "";
  const ext = fileName.split(".").pop().toLowerCase();

  if (["jpg", "jpeg", "png", "gif", "bmp", "webp"].includes(ext)) {
    previewFileType.value = "image";
  } else if (ext === "pdf") {
    previewFileType.value = "pdf";
  } else if (["doc", "docx"].includes(ext)) {
    previewFileType.value = "word";
  } else if (["xls", "xlsx"].includes(ext)) {
    previewFileType.value = "excel";
  } else {
    previewFileType.value = "other";
  }

  console.log("Preview file type:", previewFileType.value);
  previewDialogVisible.value = true;
}
function handlePrevStep() {
  if (activeStep.value > 0) {
    activeStep.value--;
    goStep(activeStep.value);
  }
}

function handleNextStep() {
  if (activeStep.value < steps.length - 1) {
    if (getPersistedParam("companyStatus") <= 2 && activeStep.value > 0) {
      return proxy.$modal.msgWarning("请完成合同环节后再操作");
    } else {
      activeStep.value++;
      goStep(activeStep.value);
    }
  }
}

// 监听路由变化，持久化companyId/companyStatus/companyClass
watch(
  () => [
    route.query.companyId,
    route.query.companyStatus,
    route.query.companyClass,
    route.query.entryMode,
  ],
  ([id, status, cclass, entryMode]) => {
    if (id) persistParam("companyId", id);
    if (status) persistParam("companyStatus", status);
    if (cclass) persistParam("companyClass", cclass);
    if (cclass) companyClass.value = cclass;
    if (entryMode) persistParam("entryMode", entryMode);
  }
);

// 上传前处理，调用companyUploadFile接口
async function beforeUpload(file, tag) {
  const companyId = route.query.companyId || route.params.companyId;
  const formData_company = new FormData();
  formData_company.append("companyId", companyId);
  formData_company.append("file", file);
  formData_company.append("tag", tag);
  try {
    const res = await companyUploadFile(formData_company);
    if (tag == 12) {
      await updateCertification({ companyId: companyId, certificationStatus: 2 });
    }
    // 上传成功后刷新文件列表
    await refreshFileListByTag(tag);

    return false; // 阻止el-upload默认上传
  } catch (e) {
    proxy.$modal.msgWarning("网络繁忙, 请稍后重试");
    return false;
  }
}

// 刷新单个tag的文件列表
async function refreshFileListByTag(tag) {
  const companyId = route.query.companyId || route.params.companyId;
  const params = {
    pageNum: 1,
    pageSize: 20,
    companyId,
    tag,
  };
  try {
    const res = await getFileByCompanyIdAndTag(params);
    const files = ((res && res.rows) || []).map((f) => ({
      id: f.id,
      name: f.name || "",
      url: f.url,
    }));
    if (tag === 0) fileListRecord.value = files;
    else if (tag === 13) fileListRecordOk.value = files;
    else if (tag === 1) fileListInfo.value = files;
    else if (tag === 2) fileListSign.value = files;
    else if (tag === 3) fileListId.value = files;
    else if (tag === 4) fileListLicense.value = files;
    else if (tag === 7) fileListContractArchive.value = files;
    else if (tag === 14) fileListVirtualArchive.value = files;
    else if (tag === 15) fileListBeforeDecoration.value = files;
    else if (tag === 16) fileListAfterDecoration.value = files;
    else if (tag === 9) fileListPropertyHandover.value = files;
    else if (tag === 11) fileListPlanPdf.value = files;
    else if (tag === 19) fileListPlanZip.value = files;
    else if (tag === 17) fileListWaterMeter.value = files;
    else if (tag === 18) fileListElectricMeter.value = files;
    else if (tag === 12) fileListLicensePdf.value = files;
  } catch (e) {
    // 可选： proxy.$modal.msgError("文件刷新失败");
  }
}

// 删除文件
async function handleFileRemove(type, file) {
  if (!file.id) {
    // 归档文件上传后el-upload会自动触发on-remove，临时文件无id，直接忽略不报错
    return;
  }
  try {
    await deleteFile({ id: file.id });
    // 删除后刷新对应tag的文件列表
    let tag = 0;
    if (type === "record") tag = 0;
    else if (type === "record_ok") tag = 13;
    else if (type === "info") tag = 1;
    else if (type === "sign") tag = 2;
    else if (type === "id") tag = 3;
    else if (type === "license") tag = 4;
    else if (type === "contractArchive") tag = 7;
    else if (type === "virtualArchive") tag = 14;
    await refreshFileListByTag(tag);
    proxy.$modal.msgSuccess("删除成功");
  } catch (e) {
    console.error("删除失败:", e);
  }
}

const steps = [
  { label: "备案", value: "record", icon: "UploadFilled" },
  { label: "合同", value: "contract", icon: "Edit" },
  { label: "办证", value: "property", icon: "Picture" },
  { label: "入驻告知", value: "notice", icon: "CircleCheckFilled" },
];

function downloadTemplate() {
  console.log("下载备案表模板");
  const a = document.createElement("a");
  a.href =
    "https://file-1310994275.cos.ap-nanjing.myqcloud.com/template/001科技人才局项目备案申请表.xlsx";
  a.download = "备案表模板.docx";
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}
function downloadDesc() {
  console.log("下载信息注册表说明");
  const a = document.createElement("a");
  a.href =
    "https://file-1310994275.cos.ap-nanjing.myqcloud.com/template/002新设企业注册信息和材料附件.xlsx";
  a.download = "信息注册表说明.docx";
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}

// useRoute/useRouter已在顶部声明

function getStepIndexByStatus(status) {
  // 可根据实际companyStatus与步骤的映射关系调整
  const map = {
    record: 0,
    contract: 1,
    approval: 2,
    property: 3,
    notice: 4,
  };
  // status为数字时直接返回
  if (typeof status === "number") return status;
  return map[status] || 0;
}

function goStep(idx) {
  // 跳转到对应路由或页面
  // 这里假设路由格式为 /settled/step/:companyId/:step
  const companyId = route.query.companyId || route.params.companyId;
  console.log("companyStatus:", getPersistedParam("companyStatus"), "idx:", idx);
  if (getPersistedParam("companyStatus") <= 2 && idx > 1) {
    proxy.$modal.msgWarning("请完成合同环节后再操作");
    return;
  } else {
    if (idx == 1) {
      fetchFeiShuApprovalTaskMessage();
    }
    activeStep.value = idx;

    const stepKey = steps[idx].value;
    if (stepKey === "notice") {
      // 获取服务时间节点数据
      fetchServiceTimeline();
    }
  }
  // console.log(`跳转到步骤: ${stepKey}-${idx}, companyId: ${companyId}`);
  //   router.push({
  //     name: "CompanyStep",
  //     params: { companyId, step: stepKey },
  //     query: { companyId, step: stepKey },
  //   });
}

function handleStepChange(idx) {
  goStep(idx);
}
const tableData = ref([]);
const editRow = ref(-1); // 当前编辑行索引
const addRowVisible = ref(false);
const editForm = ref({
  contractNumber: "",
  cycle: "",
  unitPrice: "",
  monthPrice: "",
  startTime: "",
  amount: "",
  remake: "",
  type: "",
  flag: 0,
});

// 合同编号变化时自动刷新回款计划
watch(
  () => contractForm.value.contractNumber,
  (val) => {
    if (val) {
      // 合同编号变化时调用飞书审批任务信息接口
      fetchFeiShuApprovalTaskMessage();
      // 如果当前在开票环节，也调用开票审批任务信息接口
      if (activeStep.value === 2) {
        fetchInvoiceFeiShuApprovalTaskMessage();
      }
    }
  }
);
// 完成步骤的处理函数
function handleCompleteRecordStep(type) {
  if (type === "备案") {
    submitAndUpdate({ companyId: route.query.companyId, status: 2 })
      .then((res) => {
        proxy.$modal.msgSuccess("备案完成");
        persistParam("companyStatus", 2);
        // 更新路由参数
        router.push({
          query: {
            ...route.query,
            companyStatus: 2,
          },
        });
        // insertCertification({ companyId: route.query.companyId });

        goStep(1);
      })
      .catch((err) => {
        console.error("备案失败:", err);
      });
  } else if (type === "合同") {
    submitAndUpdate({ companyId: route.query.companyId, status: 3 })
      .then((res) => {
        proxy.$modal.msgSuccess("合同完成");
        persistParam("companyStatus", 3);
        router.push({
          query: {
            ...route.query,
            companyStatus: 3,
          },
        });
        setTimeout(() => {
          goStep(2);
        }, 100);
      })
      .catch((err) => {
        console.error("合同失败:", err);
      });
  }

  // 可以在这里添加其他逻辑，比如更新状态等
  // 例如跳转到下一步
  // handleNextStep();
}
// 计算属性：判断是否显示完成按钮
const shouldShowCompleteButton = computed(() => {
  // 检查 companyStatus 是否为 1
  const companyStatus = getPersistedParam("companyStatus");
  if (companyStatus !== "1" && companyStatus !== 1) {
    return false;
  }

  // 检查备案表和备案情况说明表是否已上传
  const isRecordUploaded = fileListRecord.value && fileListRecord.value.length > 0;
  const isRecordOkUploaded = fileListRecordOk.value && fileListRecordOk.value.length > 0;

  if (!isRecordUploaded || !isRecordOkUploaded) {
    return false;
  }

  // 如果是新注册，还需要检查信息注册表
  const companyClass = getPersistedParam("companyClass");
  if (companyClass === "新注册" || companyClass === "新设") {
    const isInfoUploaded = fileListInfo.value && fileListInfo.value.length > 0;
    return isInfoUploaded;
  }

  // 迁址等其他情况不需要信息注册表
  return true;
});
// 计算属性：判断是否显示合同完成按钮
const shouldShowCompleteContractButton = computed(() => {
  // 检查 companyStatus 是否为 2
  const companyStatus = getPersistedParam("companyStatus");
  let companyZt =
    route.query.zt == "江环项目" || route.query.zt == "秦淮项目" ? false : true;
  let companyStatusZt = companyZt
    ? companyStatus !== "2" && companyStatus !== 2
    : companyStatus !== "1" && companyStatus !== 1;

  if (companyStatusZt) {
    return false;
  }

  // 检查实体合同归档或虚拟合同归档文件是否已上传

  const isVirtualArchiveUploaded =
    fileListVirtualArchive.value && fileListVirtualArchive.value.length > 0;
  console.log(fileListContractArchive.value.length, fileListVirtualArchive.value.length);

  return isVirtualArchiveUploaded;
});
// 添加完成当前模块的处理函数
function handleCompletePropertyStep() {
  const companyId = route.query.companyId || route.params.companyId;

  // 所有条件满足，提交更新
  submitAndUpdate({ companyId, status: 4 })
    .then((res) => {
      if (res.code === 200) {
        proxy.$modal.msgSuccess("完成当前模块");
        // 房间改为已出租状态
        handleRentRoom();
        persistParam("companyStatus", 4);
        // 更新路由参数
        router.push({
          query: {
            ...route.query,
            companyStatus: 4,
          },
        });
        goStep(3); // 跳转到入驻告知步骤
      } else {
        proxy.$modal.msgError(res.msg || "操作失败，请稍后重试");
      }
    })
    .catch((err) => {
      console.error("操作失败:", err);
    });
}

// 出租房间
function handleRentRoom() {
  const params = {
    contractNumber: contractForm.value.contractNumber,
  };
  rentRoom(params)
    .then((res) => {
      if (res.code !== 200) {
        proxy.$modal.msgError(res.msg || "房间出租失败");
      }
    })
    .catch((err) => {
      console.error("房间出租失败:", err);
    });
}

// 计算属性：判断是否显示完成当前模块按钮
const shouldShowCompletePropertyButton = computed(() => {
  // 检查 companyStatus 是否为 3
  const companyStatus = getPersistedParam("companyStatus");
  if (companyStatus !== "3" && companyStatus !== 3) {
    return false;
  }

  // 不再需要检查营业执照，直接返回true
  return true;
});
onMounted(() => {
  // 获取companyId、companyStatus、companyClass、entryMode，持久化
  const companyName = getPersistedParam("companyName");
  const zt = getPersistedParam("zt");
  const companyId = getPersistedParam("companyId");
  const companyStatus = getPersistedParam("companyStatus");
  companyClass.value = getPersistedParam("companyClass");
  const entryMode = getPersistedParam("entryMode");
  persistParam("companyId", companyId);
  persistParam("companyStatus", companyStatus);
  persistParam("companyClass", companyClass.value);
  persistParam("entryMode", entryMode);
  persistParam("companyName", companyName);
  persistParam("zt", zt);

  activeStep.value = companyStatus - 1;

  // 仅在进入页面且处于备案步骤时回显文件
  if (activeStep.value === 0 && companyId) {
    // tag: 0-备案情况说明, 1-信息注册表, 2-法人签字笔迹, 3-身份证, 4-营业执照
    // 迁址只查tag=0，新注册查tag=0,1
    let tags = [0];
    if (companyClass.value !== "迁址") {
      tags.push(1);
    }
    tags = tags.concat([2, 3, 4]); // 添加办证材料到备案环节
    tags.forEach(async (tag) => {
      const params = {
        pageNum: 1,
        pageSize: 20,
        companyId,
        tag,
      };
      try {
        const res = await getFileByCompanyIdAndTag(params);
        const files = (res && res.rows ? res.rows : []).map((f) => ({
          id: f.id,
          name: f.name || "",
          url: f.url,
        }));
        if (tag === 0) fileListRecord.value = files;
        else if (tag === 13) fileListRecordOk.value = files;
        else if (tag === 1) fileListInfo.value = files;
        else if (tag === 2) fileListSign.value = files;
        else if (tag === 3) fileListId.value = files;
        else if (tag === 4) fileListLicense.value = files;
      } catch (e) {
        // 可选： proxy.$modal.msgError("文件回显失败");
      }
    });
  } else if (activeStep.value === 1 && companyId) {
    refreshFileListVirtualArchive();
    getCarrierInfoData();
    // 进入合同环节加载空闲房号
    fetchFreeRooms();
    // 第一次进入合同环节时调用飞书审批任务信息接口
    if (contractForm.value.contractNumber) {
      fetchFeiShuApprovalTaskMessage();
    }
  } else if (activeStep.value === 2 && companyId) {
    // 初始化获取办证材料文件列表
    let tags = [2, 3, 4, 12]; // 法人签字笔迹、自然人身份证、非自然人营业执照、营业执照PDF
    tags.forEach(async (tag) => {
      const params = {
        pageNum: 1,
        pageSize: 20,
        companyId,
        tag,
      };
      try {
        const res = await getFileByCompanyIdAndTag(params);
        const files = (res && res.rows ? res.rows : []).map((f) => ({
          id: f.id,
          name: f.name || "",
          url: f.url,
        }));
        if (tag === 2) fileListSign.value = files;
        else if (tag === 3) fileListId.value = files;
        else if (tag === 4) fileListLicense.value = files;
        else if (tag === 12) fileListLicensePdf.value = files;
      } catch (e) {
        // 可选： proxy.$modal.msgError("文件回显失败");
      }
    });
  }
});
</script>

<style scoped>
.record-container {
  padding: 24px 32px 0 32px;
  /* background: #f4f6fa; */
  min-height: 100vh;
}

/* 返回按钮样式 */
.back-button-container {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e5e7ef;
  gap: 16px;
}

.back-button {
  border-radius: 8px;
  padding: 10px 20px;
  font-weight: 500;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(37, 99, 235, 0.15);
}

.back-button:hover {
  transform: translateX(-3px);
  box-shadow: 0 4px 12px rgba(37, 99, 235, 0.25);
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  flex: 1;
}
.company-main-row {
  min-height: 700px;
}
.company-main-content {
  min-height: 700px;
}
.company-step-side {
  padding-top: 8px;
}
.material-inner-row {
  display: flex;
  flex-direction: row;
  align-items: flex-start;
  gap: 24px;
}
.material-upload-row {
  display: flex;
  gap: 48px;
  margin-top: 40px;
}

.material-upload-row.stacked {
  flex-direction: column;
  gap: 24px;
}

.tip-icon {
  cursor: pointer;
  font-size: 20px;
  color: #909399;
}
.tip-icon:hover {
  color: #409eff;
}

.tip-text {
  margin-left: 6px;
  font-size: 14px;
  color: #909399;
  cursor: pointer;
}
.tip-text:hover {
  color: #409eff;
}

.property-flex-layout {
  display: flex;
  flex-direction: row;
  align-items: flex-start;
  gap: 32px;
  flex-wrap: wrap;
}

.property-left {
  width: 70%;
  min-width: 300px;
}

.property-right {
  flex: 1;
  min-width: 300px;
}

.property-uploads-wrapper {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  flex-wrap: wrap;
  gap: 24px;
}

.property-flex-layout {
  display: flex;
  flex-direction: row;
  align-items: flex-start;
  gap: 32px;
  flex-wrap: wrap;
}

.property-left {
  width: 70%;
  min-width: 300px;
}

.property-right {
  flex: 1;
  min-width: 300px;
}

.property-uploads-wrapper {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  flex-wrap: wrap;
  gap: 24px;
}

.property-upload-col {
  flex: 1;
  min-width: 300px;
}

.material-block {
  flex: 1;
  padding: 24px 32px 18px 32px;
  border-radius: 8px;
  border: 1px solid #e5e7ef;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  /* background: #fff; */
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  transition: box-shadow 0.3s ease;
}

.material-block:hover {
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.1);
}

.block-title {
  font-size: 18px;
  font-weight: 600;
  color: #2563eb;
  margin-bottom: 16px;
  position: relative;
  padding-left: 10px;
}

.block-title::before {
  content: "";
  position: absolute;
  left: 0;
  top: 2px;
  width: 4px;
  height: 20px;
  background-color: #2563eb;
  border-radius: 2px;
}

.upload-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 12px;
  width: 100%;
}

.upload-label {
  font-size: 15px;
  font-weight: 500;
  margin-bottom: 4px;
  color: #333;
}

.upload-demo {
  width: 100%;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 10px 0;
}

.step-navigation {
  display: flex;
  justify-content: space-between;
  margin-top: 32px;
  gap: 16px;
  flex-wrap: wrap;
}

.step-navigation .el-button {
  flex: 1;
  min-width: 100px;
}

.form-section-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 24px 0 16px 0;
  padding-bottom: 8px;
  border-bottom: 1px solid #eee;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 16px;
}

.form-actions {
  display: flex;
  justify-content: flex-start;
  gap: 16px;
  margin-top: 24px;
  flex-wrap: wrap;
}

.form-actions .el-button {
  min-width: 100px;
}

.table-actions {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.success {
  background-color: #f0f9ff;
  color: #0066cc;
  border: 1px solid #0066cc;
}

.status-badge.warning {
  background-color: #fff9e6;
  color: #cc9900;
  border: 1px solid #cc9900;
}

.status-badge.danger {
  background-color: #fff0f0;
  color: #cc0000;
  border: 1px solid #cc0000;
}

@media (max-width: 768px) {
  .property-flex-layout {
    flex-direction: column;
  }

  .property-left {
    width: 100%;
  }

  .property-uploads-wrapper {
    flex-direction: column;
  }

  .property-upload-col {
    min-width: 100%;
  }

  .material-upload-row {
    flex-direction: column;
    gap: 24px;
  }

  .step-navigation {
    flex-direction: column;
  }

  .step-navigation .el-button {
    width: 100%;
  }

  .form-grid {
    grid-template-columns: 1fr;
  }
}
</style>
